import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_demo/widget/buttons.dart';
import 'package:flutter_demo/widget/choose_file.dart';
import 'package:flutter_demo/widget/tiny_widgets.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'http/api.dart';
import 'package:universal_html/html.dart' as html;

class C_RegisterScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _C_RegisterScreenState();
}

class _C_RegisterScreenState extends State<C_RegisterScreen> {

  late GlobalKey _formKey;
  late TextEditingController _accountController;
  late TextEditingController _pwdController;
  late TextEditingController _pIdController;
  late TextEditingController _nameController;
  late TextEditingController _representativeController;
  late TextEditingController _levelController;
  late TextEditingController _natureController;
  late TextEditingController _industryController;
  late TextEditingController _clientController;
  late TextEditingController _addressController;
  late TextEditingController _locationController;

  late html.File _license;
  late html.File _consistent;
  late html.File _picture;

  @override
  void initState() {
    _formKey = GlobalKey<FormState>();
    _accountController = TextEditingController();
    _pwdController = TextEditingController();
    _pIdController = TextEditingController();
    _nameController = TextEditingController();
    _representativeController = TextEditingController();
    _levelController = TextEditingController();
    _natureController = TextEditingController();
    _industryController = TextEditingController();
    _clientController = TextEditingController();
    _addressController = TextEditingController();
    _locationController = TextEditingController();
  }

  @override
  Widget build(BuildContext context) {

    var cAccount = Container(
      width: 220,
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: TextFormField(
        controller: _accountController,
        decoration: const InputDecoration(
          labelText: '统一社会信用代码',
          hintText: '单位的社会信用代码',
          hintStyle: TextStyle(
            fontSize: 14,
            color: Colors.black45,
          ),
          border: InputBorder.none,
        ),
        style: TextStyle(
          fontSize: 14,
          color: Color(0xff606266),
        ),
        validator: (value) {
          if (value!.trim().isEmpty) {
            return '统一社会信用代码不能为空';
          } else if (value.trim().length > 10) {
            return '统一社会信用代码超出最大长度';
          } else {
            return null;
          }
        },
      ),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.black26, width: 1.0),
        borderRadius: BorderRadius.circular(5.0),
      ),
    );

    var cPassword = Container(
      width: 220,
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: TextFormField(
        controller: _pwdController,
        obscureText: true,
        decoration: const InputDecoration(
          labelText: '单位密码',
          hintText: '您的登录密码',
          hintStyle: TextStyle(
            fontSize: 14,
            color: Colors.black45,
          ),
          border: InputBorder.none,
        ),
        style: TextStyle(
          fontSize: 14,
          color: Color(0xff606266),
        ),
        validator: (value) {
          if (value!.trim().isEmpty) {
            return '单位密码不能为空';
          } else if (value.trim().length > 15) {
            return '单位密码超出最大长度';
          } else {
            return null;
          }
        },
      ),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.black26, width: 1.0),
        borderRadius: BorderRadius.circular(5.0),
      ),
    );

    var pId = Container(
      width: 220,
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: TextFormField(
        controller: _pIdController,
        decoration: const InputDecoration(
          labelText: '法定代表人身份证号',
          hintText: '单位的法定代表人身份证号',
          hintStyle: TextStyle(
            fontSize: 14,
            color: Colors.black45,
          ),
          border: InputBorder.none,
        ),
        style: TextStyle(
          fontSize: 14,
          color: Color(0xff606266),
        ),
        validator: (value) {
          if (value!.trim().isEmpty) {
            return '法定代表人身份证号不能为空';
          } else if (value.trim().length > 19) {
            return '法定代表人身份证号超出最大长度';
          } else {
            return null;
          }
        },
      ),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.black26, width: 1.0),
        borderRadius: BorderRadius.circular(5.0),
      ),
    );

    var cName = Container(
      width: 220,
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: TextFormField(
        controller: _nameController,
        decoration: const InputDecoration(
          labelText: '单位名称',
          hintText: '您的单位名称',
          hintStyle: TextStyle(
            fontSize: 14,
            color: Colors.black45,
          ),
          border: InputBorder.none,
        ),
        style: TextStyle(
          fontSize: 14,
          color: Color(0xff606266),
        ),
        validator: (value) {
          if (value!.trim().isEmpty) {
            return '单位名称不能为空';
          } else if (value.trim().length > 10) {
            return '单位名称超出最大长度';
          } else {
            return null;
          }
        },
      ),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.black26, width: 1.0),
        borderRadius: BorderRadius.circular(5.0),
      ),
    );

    var representative = Container(
      width: 220,
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: TextFormField(
        controller: _representativeController,
        decoration: const InputDecoration(
          labelText: '法定代表人',
          hintText: '单位的法定代表人',
          hintStyle: TextStyle(
            fontSize: 14,
            color: Colors.black45,
          ),
          border: InputBorder.none,
        ),
        style: TextStyle(
          fontSize: 14,
          color: Color(0xff606266),
        ),
        validator: (value) {
          if (value!.trim().isEmpty) {
            return '法定代表人不能为空';
          } else if (value.trim().length > 4) {
            return '法定代表人超出最大长度';
          } else {
            return null;
          }
        },
      ),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.black26, width: 1.0),
        borderRadius: BorderRadius.circular(5.0),
      ),
    );

    var level = Container(
      width: 220,
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: TextFormField(
        controller: _levelController,
        decoration: const InputDecoration(
          labelText: '单位级别',
          hintText: '您的单位级别',
          hintStyle: TextStyle(
            fontSize: 14,
            color: Colors.black45,
          ),
          border: InputBorder.none,
        ),
        style: TextStyle(
          fontSize: 14,
          color: Color(0xff606266),
        ),
        validator: (value) {
          if (value!.trim().isEmpty) {
            return '单位级别不能为空';
          } else if (value.trim().length > 4) {
            return '单位级别超出最大长度';
          } else {
            return null;
          }
        },
      ),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.black26, width: 1.0),
        borderRadius: BorderRadius.circular(5.0),
      ),
    );

    var nature = Container(
      width: 220,
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: TextFormField(
        controller: _natureController,
        decoration: const InputDecoration(
          labelText: '单位性质',
          hintText: '您的单位性质',
          hintStyle: TextStyle(
            fontSize: 14,
            color: Colors.black45,
          ),
          border: InputBorder.none,
        ),
        style: TextStyle(
          fontSize: 14,
          color: Color(0xff606266),
        ),
        validator: (value) {
          if (value!.trim().isEmpty) {
            return '单位性质不能为空';
          } else if (value.trim().length > 5) {
            return '单位性质超出最大长度';
          } else {
            return null;
          }
        },
      ),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.black26, width: 1.0),
        borderRadius: BorderRadius.circular(5.0),
      ),
    );

    var industry = Container(
      width: 220,
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: TextFormField(
        controller: _industryController,
        decoration: const InputDecoration(
          labelText: '单位行业',
          hintText: '您的单位行业',
          hintStyle: TextStyle(
            fontSize: 14,
            color: Colors.black45,
          ),
          border: InputBorder.none,
        ),
        style: TextStyle(
          fontSize: 14,
          color: Color(0xff606266),
        ),
        validator: (value) {
          if (value!.trim().isEmpty) {
            return '单位行业不能为空';
          } else if (value.trim().length > 5) {
            return '单位行业超出最大长度';
          } else {
            return null;
          }
        },
      ),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.black26, width: 1.0),
        borderRadius: BorderRadius.circular(5.0),
      ),
    );

    var client = Container(
      width: 220,
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: TextFormField(
        controller: _clientController,
        decoration: const InputDecoration(
          labelText: '单位委托人',
          hintText: '您的单位委托人',
          hintStyle: TextStyle(
            fontSize: 14,
            color: Colors.black45,
          ),
          border: InputBorder.none,
        ),
        style: TextStyle(
          fontSize: 14,
          color: Color(0xff606266),
        ),
        validator: (value) {
          if (value!.trim().isEmpty) {
            return '单位委托人不能为空';
          } else if (value.trim().length > 4) {
            return '单位委托人超出最大长度';
          } else {
            return null;
          }
        },
      ),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.black26, width: 1.0),
        borderRadius: BorderRadius.circular(5.0),
      ),
    );

    var address = Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: TextFormField(
        controller: _addressController,
        decoration: const InputDecoration(
          labelText: '单位地址',
          hintText: '您的单位地址',
          hintStyle: TextStyle(
            fontSize: 14,
            color: Colors.black45,
          ),
          border: InputBorder.none,
        ),
        style: TextStyle(
          fontSize: 14,
          color: Color(0xff606266),
        ),
        validator: (value) {
          if (value!.trim().isEmpty) {
            return '单位地址不能为空';
          } else if (value.trim().length > 25) {
            return '单位地址超出最大长度';
          } else {
            return null;
          }
        },
      ),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.black26, width: 1.0),
        borderRadius: BorderRadius.circular(5.0),
      ),
    );

    var location = Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: TextFormField(
        controller: _locationController,
        decoration: const InputDecoration(
          labelText: '单位所在地',
          hintText: '您的单位所在地',
          hintStyle: TextStyle(
            fontSize: 14,
            color: Colors.black45,
          ),
          border: InputBorder.none,
        ),
        style: TextStyle(
          fontSize: 14,
          color: Color(0xff606266),
        ),
        validator: (value) {
          if (value!.trim().isEmpty) {
            return '单位所在地不能为空';
          } else if (value.trim().length > 25) {
            return '单位所在地超出最大长度';
          } else {
            return null;
          }
        },
      ),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.black26, width: 1.0),
        borderRadius: BorderRadius.circular(5.0),
      ),
    );

    var form = Form(
      key: _formKey,
      autovalidateMode: AutovalidateMode.onUserInteraction,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          C(22),
          Wrap(
            spacing: 32,
            runSpacing: 32,
            children: [
              cAccount,
              cName,
              representative,
              pId,
              level,
              nature,
              industry,
              client,
              cPassword,
            ],
          ),
          C(32),
          location,
          C(32),
          address,
          C(32),
          Container(
            width: double.infinity,
            height: 168,
            child: Row(
              children: [
                Expanded(
                  child: section('营业执照扫描件要求',
                      '企业：《企业法人营业执照》（工商局发的）\n'
                      '事业单位：《事业单位法人证书》（人事局发的）\n'
                      '社团：《社会团体法人登记证书》（民政局发的）\n'
                      '民办非企业单位：《民办非企业单位登记证书》（民政局发的）\n'
                      '请上传彩色扫描件原件\n'
                      '政府/机关：《统一社会信用代码证书》'),
                ),
                Expanded(
                  child: section('营业执照复印件要求',
                      '保证复印件图片清晰可见，包含营业执照扫描件的各项要求'),
                ),
                Expanded(
                  child: section('经办人手持营业执照',
                      '注册经办人需手持营业执照原件，使用手机拍照请对焦到证件信息，\n'
                          '若经手机QQ/微信传输到电脑，请务必勾选原图传输。'),
                ),
              ],
            ),
          ),
          Container(
            width: double.infinity,
            height: 230,
            child: Row(
              children: [
                Expanded(
                  child: Container(
                    alignment: Alignment.topLeft,
                    child: ChoosePictureView(callback: (file) => _license = file),
                  ),
                ),
                Expanded(
                  child: Container(
                    alignment: Alignment.topLeft,
                    child: ChoosePictureView(callback: (file) => _consistent = file),
                  ),
                ),
                Expanded(
                  child: Container(
                    alignment: Alignment.topLeft,
                    child: ChoosePictureView(callback: (file) => _picture = file),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );

    return Scaffold(
      body: Scrollbar(
        child: SingleChildScrollView(
          child: Container(
            width: double.infinity,
            alignment: Alignment.center,
            padding: EdgeInsets.all(20),
            decoration: BoxDecoration(
              image: DecorationImage(
                image: NetworkImage(
                  'http://my.gxrczc.com/assets/img/bg.png',
                ),
                fit: BoxFit.cover,
              ),
            ),
            child: Container(
              width: double.infinity,
              decoration: BoxDecoration(
                color: Colors.white,
                border: Border.all(color: Colors.black26),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    width: double.infinity,
                    height: 32.8,
                    padding: EdgeInsets.symmetric(
                      horizontal: 10,
                    ),
                    decoration: BoxDecoration(
                      color: Color(0xff1a56a8),
                    ),
                    child: Row(
                      children: [
                        Expanded(
                          child: Text(
                            '用户注册',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 16,
                            ),
                          ),
                        ),
                        InkWell(
                          onTap: () => Navigator.pop(context),
                          child: Text(
                            '返回登录',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 14,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    width: double.infinity,
                    height: 1004.4,
                    padding: EdgeInsets.all(10),
                    child: Column(
                      children: [
                        Container(
                          width: double.infinity,
                          height: 923.8,
                          decoration: BoxDecoration(
                            color: Color(0xfffbfdff),
                            borderRadius: BorderRadius.circular(5),
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.stretch,
                            children: [
                              Container(
                                width: double.infinity,
                                height: 31.8,
                                alignment: Alignment.centerLeft,
                                padding: EdgeInsets.symmetric(
                                  horizontal: 10,
                                ),
                                decoration: BoxDecoration(
                                  color: Color(0xffe4f0ff),
                                  borderRadius: BorderRadius.only(
                                    topLeft: Radius.circular(5),
                                    topRight: Radius.circular(5),
                                  ),
                                ),
                                child: Text(
                                  '单位信息',
                                  style: TextStyle(
                                    color: Color(0xff1a56a8),
                                    fontSize: 16,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                              Expanded(
                                child: Container(
                                  width: double.infinity,
                                  height: double.infinity,
                                  padding: EdgeInsets.only(
                                    left: 10,
                                    right: 10,
                                    top: 10,
                                  ),
                                  child: form,
                                ),
                              ),
                            ],
                          ),
                        ),
                        C(20),
                        Container(
                          width: double.infinity,
                          height: 40.6,
                          alignment: Alignment.bottomRight,
                          child: BaseButton(
                            radius: 5,
                            width: 84,
                            height: 40,
                            withShadow: false,
                            centerButton: false,
                            buttonColor: Color(0xff1A56A8),
                            onTap: () {
                              if ((_formKey.currentState as FormState).validate())
                                validatePassed(context);
                            },
                            child: Text(
                              '创建用户',
                              style: TextStyle(
                                fontSize: 14,
                                color: Colors.white,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  void validatePassed(BuildContext context) {

    html.FormData formData = html.FormData();
    formData.append('cAccount', _accountController.text);
    formData.append('cPassword', _pwdController.text);
    formData.append('pId', _pIdController.text);
    formData.append('cName', _nameController.text);
    formData.append('representative', _representativeController.text);
    formData.append('level', _levelController.text);
    formData.append('nature', _natureController.text);
    formData.append('industry', _industryController.text);
    formData.append('client', _clientController.text);
    formData.appendBlob('license', _license.slice());
    formData.append('address', _addressController.text);
    formData.append('location', _locationController.text);
    formData.appendBlob('consistent', _consistent.slice());
    formData.appendBlob('picture', _picture.slice());

    var request = html.HttpRequest();
    request.open('POST', SystemApi.baseUrl + 'c_register');
    request.send(formData);

    request.onLoadEnd.listen((event) {
      print('[HttpRequest] response ${request.responseText!}');
      var map = json.decode(request.responseText!);
      if (request.status == 200 && map['code'] == '1') {
        Fluttertoast.showToast(msg: map['msg']);
        Navigator.pop(context);
      } else if (map['code'] != '1') {
        Fluttertoast.showToast(msg: map['msg']);
      } else {
        Fluttertoast.showToast(msg: request.status.toString());
      }
    });
  }
  
  Widget section(String title, String subTitle) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Text(
          title,
          style: TextStyle(
            fontSize: 18.72,
            fontWeight: FontWeight.bold,
            color: Color(0xff303133),
          ),
        ),
        Expanded(
          child: Container(
            alignment: Alignment.topLeft,
            margin: EdgeInsets.symmetric(
              vertical: 14,
            ),
            child: Text(
              subTitle,
              style: TextStyle(
                fontSize: 14,
                color: Color(0xffd9524e),
              ),
            ),
          ),
        ),
      ],
    );
  }
}